//
//  ZCPutInStorageViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/29.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCPutInStorageViewController.h"
#import "ZCTaskTitleView.h"
#import "ZCPutInStorageTableViewCell.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCPutInStoragePlanModel.h"
#import "ZCPutInStoragePlanDetailViewController.h"


static NSString *taskListCell = @"ZCPutInStorageTableViewCell";
static NSString *taskTotalNumCell = @"ZCTaskTotalNumTableViewCell";

@interface ZCPutInStorageViewController ()<ZCTaskTitleViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) ZCTaskTitleView *taskTitleView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *taskArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger taskType;
@property (nonatomic, strong) ZCPutInStoragePlanModel *planModel;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCPutInStorageViewController
#pragma mark - 懒加载
- (NSMutableArray *)taskArray {
    if (!_taskArray) {
        _taskArray = [NSMutableArray array];
    }
    return _taskArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, space(80) + 64, SCREENWIDTH, SCREENHEIGHT - space(80) - 64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = ZCColor(0xf7f8fb, 1);
        
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_tableView registerClass:[ZCPutInStorageTableViewCell class] forCellReuseIdentifier:taskListCell];
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:taskTotalNumCell];
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    return _tableView;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"入库计划";
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, space(30), space(30))];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftButtonToBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.taskTitleView = [[ZCTaskTitleView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, space(80))];
    self.taskTitleView.delegate = self;
    self.taskTitleView.titleArray = @[@"未入库", @"已入库"];
    [self.view addSubview:self.taskTitleView];
    
    [self.view addSubview:self.tableView];
    self.taskType = 10;
    self.page = 1;
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self.hud showAnimated:YES];
    [self loadDataWithTaskType:self.taskType];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 按钮点击
- (void)leftButtonToBack {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网络请求
- (void)loadNewData {
    [self loadDataWithTaskType:self.taskType];
}

- (void)loadDataWithTaskType:(NSInteger)type {
    self.page = 1;
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:@(type) forKey:@"status"];
        [params setObject:@(self.page) forKey:@"current"];
        [params setObject:@(10) forKey:@"size"];
        [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId] forKey:@"houseId"];
        
        [ZCHttpTool postWithURL:SelectPlanByPage params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                [self.taskArray removeAllObjects];
                
                self.planModel = [ZCPutInStoragePlanModel yy_modelWithDictionary:responseObject[@"data"]];
                [self.taskArray addObjectsFromArray:self.planModel.records];
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView reloadData];
                if (self.taskArray.count < 10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableView.mj_footer resetNoMoreData];
                }
                [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];
            }else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.hud showAnimated:YES];
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                });
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.hud showAnimated:YES];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            });
            
        }];
    });
    
}

- (void)loadMoreData {
    [self loadMoreDataWithTaskType:self.taskType];
}

- (void)loadMoreDataWithTaskType:(NSInteger)type {
    self.page++;
    __weak typeof(self)weakSelf = self;
    if (self.page <= [self.planModel.pages integerValue]) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:@(type) forKey:@"status"];
            [params setObject:@(self.page) forKey:@"current"];
            [params setObject:@(10) forKey:@"size"];
            [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId] forKey:@"houseId"];
            
            [ZCHttpTool postWithURL:SelectPlanByPage params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    weakSelf.planModel = [ZCPutInStoragePlanModel yy_modelWithDictionary:responseObject[@"data"]];
                    [weakSelf.taskArray addObjectsFromArray:self.planModel.records];
                    
                    [weakSelf.tableView reloadData];
                    if (weakSelf.taskArray.count < 10) {
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                }else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.hud showAnimated:YES];
                        weakSelf.hud.mode = MBProgressHUDModeText;
                        weakSelf.hud.label.text = responseObject[@"message"];
                        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                    });
                }
                
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                self.page--;
                [weakSelf.tableView.mj_footer endRefreshing];
            }];
        });
    }else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    
}

#pragma mark - ZCTaskTitleViewDelegate
- (void)taskTitleViewButttonWithTitle:(NSString *)title {
    if ([title isEqualToString:@"未入库"]) {
        self.taskType = 10;
    }else if ([title isEqualToString:@"已入库"]) {
        self.taskType = 30;
    }
    [self.hud showAnimated:YES];
    [self loadDataWithTaskType:self.taskType];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.taskArray.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        ZCTaskTotalNumTableViewCell *numCell = [tableView dequeueReusableCellWithIdentifier:taskTotalNumCell forIndexPath:indexPath];
        numCell.selectionStyle = UITableViewCellSelectionStyleNone;
        numCell.num = [self.planModel.total integerValue];
        numCell.line = NO;
        return numCell;
    }else {
        
        ZCPutInStorageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:taskListCell forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        ZCStoragePlanInfoModel *infoModel = (ZCStoragePlanInfoModel *)self.taskArray[indexPath.section - 1];
        cell.typeTitle = @"车型";
        cell.statusTitle = @"状态";
        cell.planModel = infoModel;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return space(80);
    }else {
        return space(360);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCPutInStoragePlanDetailViewController *detailVC = [[ZCPutInStoragePlanDetailViewController alloc] init];
    ZCStoragePlanInfoModel *infoM = (ZCStoragePlanInfoModel *)self.taskArray[indexPath.section - 1];
    detailVC.houseId = self.planModel.condition.houseId;
    detailVC.key = infoM.Id;
    detailVC.isClick = YES;
    detailVC.fromPlan = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}



@end
